<?php
set_time_limit(60);
/**
 * 授权登录插件
 */
class loginControl  extends BaseHomeControl{

    public function __construct()
    {
        parent::__construct();
        Language::read("home_login_index");
        Language::read("home_login_register");
        Tpl::setLayout('login_register_layout');
    }
    /**
     * 获取用户模型
     * @return memberModel
     */
    protected function _getMemberModel(){
        return Model('member');
    }
    /**
     * 获取用户授权登录模型
     * @return member_oauthModel
     */
    protected function _getMemberOauthModel(){
        return Model('member_oauth');
    }
    /**
     * @return ucenterModel
     */
    protected function _getUcenterModel(){
        return Model('ucenter');
    }
    /**
     * @return pointsModel
     */
    protected function _getPointsModel(){
        return Model('points');
    }
    /**
     * @return cartModel
     */
    protected function _getCartModel(){
        return Model('cart');
    }

    /**
     *
     * @return goodsModel
     */
    protected function _getGoodsModel(){
        return Model('goods');
    }

    /**
     * @return  void
     */
    protected function _setRef_url(){
        if(isset($_SERVER['HTTP_REFERER'])&&!$_SESSION['ref_url']&&!strpos('login',$_SERVER['HTTP_REFERER'])&&preg_match('/^'.preg_quote(SHOP_SITE_URL,'/').'/',$_SERVER['HTTP_REFERER'])){
            $_SESSION['ref_url']=$_SERVER['ref_url']=$_GET['ref_url']=$_POST['ref_url']=$_SERVER['HTTP_REFERER'];
        }
    }
    protected $_login_devices=array('wap'=>1);
    /**
     * 注册登录首页
     * @return  void
     */
    public function indexOp(){
        Language::read("home_login_index");
        Language::read("home_login_register");
        if(isset($_SESSION['oauth_info'])&&$_SESSION['oauth_info']&&is_array($_SESSION['oauth_info'])){
            Language::read("home_login_register,home_login_index,home_sconnect");
            Tpl::setLayout('home_layout');
            $memberOauthModel=$this->_getMemberOauthModel();
            //获取绑定信息
            $oauth_info=$memberOauthModel->getBindInfo($_SESSION['oauth_info']);
            $oauth_login=C('oauth_login');
            $oauth_form=$_SESSION['oauth_info']['oauth_form'];
            $oauth_form_name=$oauth_login[$oauth_form]['name'];
            //检查登录状态
            if($_SESSION['is_login'] == '1') {
                //已经登录,绑定信息已存在则提示
                if($oauth_info&&$_SESSION['member_id']!==$oauth_info['member_id']){
                    showMessage('你的'.$oauth_form_name.'平台帐号 '.$oauth_info['oauth_user_name'].'已在本站绑定了其它帐号','','html','error');
                    return;
                }
                //进行绑定
                $res=$memberOauthModel->bindOauth($_SESSION['member_id'],$oauth_info);
                if ($res){
                    showMessage($oauth_form_name.'平台帐号绑定成功','index.php?act=member_connect&op='.$oauth_form.'bind');
                }else {
                    showMessage($oauth_form_name.'平台帐号绑定失败','index.php?act=member_connect&op='.$oauth_form.'bind','html','error');
                }
            }elseif($oauth_info){
                //授权信息已存在则自动登录
                $memberModel=$this->_getMemberModel();
                $member_info=$memberModel->getMemberInfo(array('member_id'=>$oauth_info['member_id']));
                if($member_info){
                    //更新授权信息
                    $memberOauthModel->refreshOauth($oauth_info['member_id'],$_SESSION['oauth_info']);
                }
                //删除授权登录信息
                unset($_SESSION['oauth_info']);
                $login_device=isset($_SESSION['login_device'])&&isset($this->_login_devices[$_SESSION['login_device']])?$_SESSION['login_device']:'';
                //进行登录
                $member_info=$this->login($member_info,$login_device);
                if($login_device){
                    switch($login_device){
                        case 'wap':
                            $_SESSION=array();
                            $_SESSION['login_wap_user']=$member_info;
                            header('location: '.MOBILE_SITE_URL.'/index.php?act=login&op=oauthLoginToken');
                            break;
                    }
                }
            }else{
                //授权信息不存进行注册或绑定
                $this->oauth_registerOp();
            }
        }else{
            $this->loginOp();
        }
    }
    /**
     * 图片下载函数
     * @var array
     */
    protected $_imageFuns = array(
        'jpeg' => array('imagecreatefromjpeg', 'imagejpeg', 'jpg'),
        'png' => array('imagecreatefrompng', 'imagepng', 'png'),
        'bmp' => array('imagecreatefrombmp', 'imagebmp', 'bmp'),
        'gif' => array('imagecreatefromgif', 'imagegif', 'gif'),
        'vnd.wap.wbmp' => array('imagecreatefromwbmp', 'imagewbmp', 'bmp'),
        'xbm' => array('imagecreatefromxbm', 'imagexbm', 'xbm'),
    );

    /**
     * 授权登录注册
     * @return  void
     */
    public function oauth_registerOp(){
        $this->_setRef_url();
        if(!isset($_SESSION['oauth_info'])||!$_SESSION['oauth_info']||!is_array($_SESSION['oauth_info'])){
            showMessage('非法访问',urlShop('login'),'html','error');
            return;
        }
        $oauth_form=$_SESSION['oauth_info']['oauth_form'];
        $oauth_login=C('oauth_login');
        $oauth_form_name=$oauth_login[$oauth_form]['name'];
        //判断来源方式
        $login_device=isset($_SESSION['login_device'])&&isset($this->_login_devices[$_SESSION['login_device']])?$_SESSION['login_device']:'';

        $result = chksubmit(false,$login_device?false:C('captcha_status_register'),'num');
        if ($result !== false){
            if ($result === -11){
                showDialog(Language::get('login_usersave_code_isnull'));
            }elseif ($result === -12){
                showDialog(Language::get('login_usersave_wrong_code'));
            }
        }else{
            //显示绑定页面
            if($login_device){
                switch($login_device){
                    case 'wap':
                        $_SESSION=array('oauth_info'=>$_SESSION['oauth_info'],'login_device'=>$login_device);
                        setcookie('oauth_name',$_SESSION['oauth_info']['oauth_user_name']);
                        setcookie('oauth_form',$_SESSION['oauth_info']['oauth_form']);
                        header('location: '.WAP_SITE_URL.'/tmpl/member/oauth.html');
                        break;
                    default:
                        Tpl::output('oauth_info',$_SESSION['oauth_info']);
                        Tpl::output('oauth_form_name',$oauth_form_name);
                        Tpl::output('nchash',substr(md5(SHOP_SITE_URL.$_GET['act'].$_GET['op']),0,8));
                        Tpl::showpage('oauth_login');
                        break;
                }
            }
           exit;
        }
        $register_info=array();
        $register_info['username'] = $_POST['user_name'];
        $register_info['password'] = $_POST['password'];
        $register_info['password_confirm'] = $_POST['password_confirm'];
        $register_info['email'] = $_POST['email'];
        $register_info['member_tel'] = $_POST['member_tel'];
        //处理头像
        $oauth_info=$_SESSION['oauth_info'];

        $member_info=$this->register($register_info,'oauth');
        if(is_string($member_info)){
            //判断登录方式
            if($login_device){
                switch($login_device){
                    case 'wap':
                        //createLoginToken
                        output_data(array('error' => $member_info));
                        break;
                    default:
                        showDialog($member_info);
                        break;
                }
            }
            return;
        }
        $member_model=$this->_getMemberModel();
        if($oauth_info['oauth_user_avatar']){
            $imageInfo = getimagesize($oauth_info['oauth_user_avatar']);
            if($imageInfo){
                $type = substr(strrchr($imageInfo['mime'], '/'), 1);
                $func = isset($this->_imageFuns[$type]) ? $this->_imageFuns[$type] : $this->_imageFuns['jpeg'];
                list($create_image, $save_image, $ext) = $func;
                $member_avatar='avatar_'.$member_info['member_id'].'.'.$ext;
                $avatarData=file_get_contents($oauth_info['oauth_user_avatar']);
                if($avatarData){
                    file_put_contents(BASE_UPLOAD_PATH.'/'.ATTACH_AVATAR.'/'.$member_avatar,$avatarData);
                    $member_info['member_avatar']=$member_avatar;
                    $member_model->update(array('member_avatar'=>$member_avatar),array('where'=>array('member_id'=>$member_info['member_id'])));
                }
            }
        }
        //添加用户绑定信息
        $memberOauthModel=$this->_getMemberOauthModel();
        $memberOauthModel->bindOauth($member_info['member_id'],$oauth_info);
        //删除授权登录信息
        unset($_SESSION['oauth_info']);
        //判断登录方式
        if($login_device){
            switch($login_device){
                case 'wap':
                    //createLoginToken
                    $token=createLoginToken($member_info['member_id'], $member_info['member_name'],'wap');
                    $_SESSION=array();
                    output_data(array('username' => $member_info['member_name'], 'key' => $token));
                    break;
                default:
                    showMessage(Language::get('login_usersave_regist_success'),urlShop('shop','index'));
                    break;
            }
        }
    }

    /**
     * 授权登录
     * @return  void
     */
    public function oauth_loginOp(){
        $this->_setRef_url();
        if(!isset($_SESSION['oauth_info'])||!$_SESSION['oauth_info']||!is_array($_SESSION['oauth_info'])){
            showMessage('非法访问',urlShop('login'),'html','error');
            return;
        }
        //判断来源方式
        $login_device=isset($_SESSION['login_device'])&&isset($this->_login_devices[$_SESSION['login_device']])?$_SESSION['login_device']:'';
        $oauth_form=$_SESSION['oauth_info']['oauth_form'];
        $oauth_login=C('oauth_login');
        $oauth_form_name=$oauth_login[$oauth_form]['name'];
        $result = chksubmit(false,$login_device?false:C('captcha_status_login'),'num');
        if ($result !== false){
            if ($result === -11){
                showDialog(Language::get('login_index_login_illegal'));
            }elseif ($result === -12){
                showDialog(Language::get('login_usersave_wrong_code'));
            }
        }else{
            Tpl::output('oauth_info',$_SESSION['oauth_info']);
            Tpl::output('oauth_form_name',$oauth_form_name);

            Tpl::output('nchash',getNchash('oauth_login'));
            Tpl::showpage('oauth_login');exit;
        }
        //登录验证
        $obj_validate = new Validate();
        $obj_validate->validateparam = array(
            array("input"=>$_POST["user_name"],		"require"=>"true", "message"=>Language::get('login_index_username_isnull')),
            array("input"=>$_POST["password"],		"require"=>"true", "message"=>Language::get('login_index_password_isnull'))
        );

        $error = $obj_validate->validate();
        if ($error != ''){
            showMessage(Language::get('error').$error,'','html','error');
        }
        $model_member = $this->_getMemberModel();
        $array	= array();
        $array['member_name']	= trim($_POST['user_name']);
        $array['member_passwd']	= md5(trim($_POST['password']));
        //用户登录
        $member_info=$this->login($model_member->infoMember(array(
            'member_name'=>$_POST['user_name'],
            'member_passwd'=>md5($_POST['password']),
        )),'oauth');
        $oauth_info=$_SESSION['oauth_info'];
        //进行帐号绑定
        $memberOauthModel=$this->_getMemberOauthModel();
        $memberOauthModel->bindOauth($member_info['member_id'],$oauth_info);
        //判断登录方式
        if($login_device){
            switch($login_device){
                case 'wap':
                    //createLoginToken
                    if(is_array($member_info)){
                        $token=createLoginToken($member_info['member_id'], $member_info['member_name'],'wap');
                        session_unset();
                        session_destroy();
                        output_data(array('username' => $member_info['member_name'], 'key' => $token));
                    }else{
                        output_data(array('error'=>$member_info));
                    }
                    break;
                default:
                    if(is_string($member_info)){
                        showDialog($member_info);
                    }else{
                        //删除授权登录信息
                        unset($_SESSION['oauth_info']);
                        showMessage('帐号绑定成功',urlShop('shop','index'));
                    }
                    break;
            }
        }
    }
    public function unbindOp(){
        $oauth_login=C('oauth_login');
        if(!isset($_SESSION['member_id'])||!$_POST['oauth_form']||!isset($oauth_login[$_GET['oauth_form']])){
            showMessage('非法访问',urlShop('login'),'html','error');
            return;
        }
        $oauth_form=$_GET['oauth_form'];
        $oauth_login=C('oauth_login');
        $oauth_form_name=$oauth_login[$oauth_form]['name'];

        $update_arr = array();
        if ($_POST['is_editpw'] == 'yes'){
            //修改密码
            $model_member	= $this->_getMemberModel();
            /**
             * 填写密码信息验证
             */
            $obj_validate = new Validate();
            $obj_validate->validateparam = array(
                array("input"=>$_POST["new_password"],		"require"=>"true","validator"=>"Length","min"=>6,"max"=>20,"message"=>Language::get('member_sconnect_password_null')),
                array("input"=>$_POST["confirm_password"],	"require"=>"true","validator"=>"Compare","operator"=>"==","to"=>$_POST["new_password"],"message"=>Language::get('member_sconnect_input_two_password_again')),
            );
            $error = $obj_validate->validate();
            if ($error != ''){
                showMessage($error,'','html','error');
            }
            $update_arr['member_passwd'] = md5(trim($_POST['new_password']));
            $edit_state		= $model_member->updateMember($update_arr,$_SESSION['member_id']);
            if(!$edit_state) {
                showMessage(Language::get('member_sconnect_password_modify_fail'),'','html','error');
            }
        }
        $memberOauthModel=$this->_getMemberOauthModel();
        $memberOauthModel->unbind($_SESSION['member_id'],$oauth_form);
        session_unset();
        session_destroy();
        showMessage('成功解除'.$oauth_form_name.'账号绑定','index.php?act=login&ref_url='.urlencode('index.php?act=member_sconnect&op=sinabind'));
    }
    /**
     * 显示登录页面
     * @return  void
     */
    public function loginOp(){
        $this->_setRef_url();
        //检查登录状态
        $this->_checkLoginMember('index');
        Language::read("home_login_index");
        Language::read("home_login_register");
        $lang = Language::getLangContent();
        $result = chksubmit(true, C('captcha_status_login'), 'num');
        $model_member = $this->_getMemberModel();
        if ($result !== false) {
            if ($result === -11) {
                showDialog($lang['login_index_login_illegal']);
            } elseif ($result === -12) {
                showDialog($lang['login_index_wrong_checkcode']);
            }
            if (processClass::islock('login')) {
                showDialog($lang['nc_common_op_repeat'], SHOP_SITE_URL);
            }
            $obj_validate = new Validate();
            $obj_validate->validateparam = array(
                array("input" => $_POST["user_name"], "require" => "true", "message" => $lang['login_index_username_isnull']),
                array("input" => $_POST["password"], "require" => "true", "message" => $lang['login_index_password_isnull']),
            );
            $error = $obj_validate->validate();
            if ($error) {
                showValidateError($error);
            }else{
                //用户登录
                $this->login($model_member->infoMember(array(
                    'member_name'=>$_POST['user_name'],
                    'member_passwd'=>md5($_POST['password']),
                )));
            }
            return;
        }
        //登录表单页面
        if (empty($_GET['ref_url'])) {
            $ref_url = getReferer();
            if (!preg_match('/act=login&op=logout/', $ref_url)) {
                $_GET['ref_url'] = $ref_url;
            }
        }
        Tpl::output('html_title', C('site_name') . ' - ' . $lang['login_index_login']);
        if ($_GET['inajax'] == 1) {
            Tpl::showpage('login_inajax', 'null_layout');
        } else {
            Tpl::output('route_op', 'index');
            Tpl::showpage('login_register');
        }
        return;
    }
    /**
     * 退出操作
     */
    public function logoutOp()
    {
        Language::read("home_login_index");
        $lang = Language::getLangContent();
        session_unset();
        session_destroy();
        setNcCookie('goodsnum', '', -3600);
        /**
         * 同步登录通知
         */
        if (C('ucenter_status')) {
            /**
             * Ucenter处理
             */
            $model_ucenter = Model('ucenter');
            $out_str = $model_ucenter->userLogout();
            $lang['login_logout_success'] = $lang['login_logout_success'] . $out_str;
            if (empty($_GET['ref_url'])) {
                $ref_url = getReferer();
            } else {
                $ref_url = $_GET['ref_url'];
            }
        }
        showMessage($lang['login_logout_success'], urlShop('shop','index',array('ref_url'=>$ref_url)), 'html', 'succ', 1, 2000);
    }

    /**
     * 会员注册页面
     */
    public function registerOp()
    {
        Language::read("home_login_index");
        Language::read("home_login_register");
        $lang = Language::getLangContent();
        $model_member = $this->_getMemberModel();
        $model_member->checkloginMember();
        Tpl::output('html_title', C('site_name') . ' - ' . $lang['login_register_join_us']);
        Tpl::output('route_op', 'register');
        Tpl::showpage('login_register');
    }
    /**
     * 用户登录
     * @param array|mixed $member_info 从用户表中检索出来的信息
     * @param string $form 登录来源方式
     * @return  void|array
     */
    protected function login($member_info,$form=''){
        $this->_setRef_url();
        $model_member=$this->_getMemberModel();
        $lang = Language::getLangContent();
        if(!$member_info){
            processClass::addprocess('login');
            if(!$form){
                showDialog($lang['login_index_login_fail']);
            }
            return $lang['login_index_login_fail'];
        }elseif(!$member_info['member_state']) {
            showDialog($lang['login_index_account_stop']);
        }
        if (C('ucenter_status')) {
            $model_ucenter = $this->_getUcenterModel();
            $member_id = $model_ucenter->userLogin(trim($_POST['user_name']), trim($_POST['password']));
            if (intval($member_id) == 0) {
                if($form){
                    return $lang['login_index_login_again'];
                }else{
                    showDialog($lang['login_index_login_again']);
                }
            }
        }
        $model_member->createSession($member_info);
        processClass::clear('login');
        // cookie中的cart存入数据库
        $this->mergecart($member_info);
        //添加会员积分
        if (C('points_isuse')) {
            //一天内只有第一次登录赠送积分
            if (trim(@date('Y-m-d', $member_info['member_login_time'])) != trim(date('Y-m-d'))) {
                $points_model = $this->_getPointsModel();
                $points_model->savePointsLog('login', array('pl_memberid' => $member_info['member_id'], 'pl_membername' => $member_info['member_name']), true);
            }
        }
        if($form){
            return $member_info;
        }
        if (C('ucenter_status')) {
            $extrajs = $model_ucenter->outputLogin($member_info['member_id'], trim($_POST['password']));
        } elseif (empty($_GET['inajax'])&&$_POST['ref_url']) {
            @header('location: ' . $_POST['ref_url']);
            exit();
        }
        if (isset($_POST['ref_url']) && isset($extrajs)) {
            showDialog($lang['login_index_login_success'], $_POST['ref_url'], 'succ', $extrajs);
        } elseif($_SESSION['ref_url']) {
            $ref_url=$_SESSION['ref_url'];
            unset($_SESSION['ref_url']);
            showDialog($lang['login_index_login_success'], $ref_url?:urlShop('shop', 'index'), 'succ');
        }else{
            showDialog($lang['login_index_login_success'], urlShop('shop', 'index'), 'succ');
        }
    }
    /**
     * 会员添加操作
     * @return  void
     */
    public function usersaveOp()
    {
        //重复注册验证
        Language::read("home_login_register");
        $lang = Language::getLangContent();
        $result = chksubmit(true, C('captcha_status_login'), 'num');
        if ($result !== false) {
            if ($result === -11) {
                showDialog($lang['invalid_request']);
            } elseif ($result === -12) {
                showDialog($lang['login_usersave_wrong_code']);
            }
        }
        $register_info = array();
        $register_info['username'] = $_POST['user_name'];
        $register_info['password'] = $_POST['password'];
        $register_info['password_confirm'] = $_POST['password_confirm'];
        $register_info['email'] = $_POST['email'];
        $register_info['member_tel'] = $_POST['member_tel'];
        $this->register($register_info);
    }

    /**
     * 注册用户
     * @param array $register_info
     * @param string $form
     * @return array
     */
    public function register(array $register_info,$form=''){
        //重复注册验证
        if (processClass::islock('reg')) {
            showDialog(Language::get('nc_common_op_repeat'), 'index.php');
        }
        Language::read("home_login_register");
        $lang = Language::getLangContent();
        $model_member = $this->_getMemberModel();
        //检查用户名
        $check_member_name	= $model_member->infoMember(array('member_name'=>trim($register_info['username'])));
        if(is_array($check_member_name) and count($check_member_name)>0) {
            showMessage(Language::get('login_usersave_your_username_exists'),'','html','error');
        }
        //检查邮箱
        $check_member_email	= $model_member->infoMember(array('member_email'=>trim($register_info['email'])));
        if(is_array($check_member_email) and count($check_member_email)>0) {
            showMessage(Language::get('login_usersave_your_email_exists'),'','html','error');
        }
        //进行注册
        $member_info = $model_member->register($register_info);
        if (!isset($member_info['error'])) {
            if (C('ucenter_status')) {
                /**
                 * Ucenter处理
                 */
                $model_ucenter = $this->_getUcenterModel();
                $uid = $model_ucenter->addUser($register_info['username'],$register_info['password'], $register_info['email']);
                if ($uid < 1) showMessage($lang['login_usersave_regist_fail'], '', 'html', 'error');
                $register_info['member_id'] = $uid;
            }
            $model_member->createSession($member_info);
            processClass::addprocess('reg');
            $this->mergecart();
            $_REQUEST['ref_url'] = (strstr($_REQUEST['ref_url'], 'logout') === false && !empty($_REQUEST['ref_url']) ? $_REQUEST['ref_url'] : 'index.php?act=member&op=home');
            if($form) return $member_info;
            showDialog(str_replace('site_name', C('site_name'), $lang['login_usersave_regist_success_ajax']), $_REQUEST['ref_url'], 'succ', '', 3);
        } else {
            if($form) return $member_info['error'];
            showDialog($member_info['error']);
        }
    }
    /**
     * 会员名称检测
     * @return  void
     */
    public function check_memberOp()
    {
        if (C('ucenter_status')) {
            /**
             * 实例化Ucenter模型
             */
            $model_ucenter = $this->_getUcenterModel();
            $result = $model_ucenter->checkUserExit(trim($_GET['user_name']));
            if ($result == 1) {
                echo 'true';
            } else {
                echo 'false';
            }
        } else {
            /**
             * 实例化模型
             */
            $model_member =$this->_getMemberModel();

            $check_member_name = $model_member->infoMember(array('member_name' => trim($_GET['user_name'])));
            if (is_array($check_member_name) and count($check_member_name) > 0) {
                echo 'false';
            } else {
                echo 'true';
            }
        }
    }

    /**
     * 登录之后,把登录前购物车内的商品加到购物车表
     *
     */
    private function mergecart($member_info = array())
    {
        if (!$member_info['member_id']) return;
        $model_cart = $this->_getCartModel();
        $save_type = C('cache.type') != 'file' ? 'cache' : 'cookie';
        $cart_new_list = $model_cart->listCart($save_type);
        if (empty($cart_new_list)) return;
        //取出当前DB购物车已有信息
        $cart_cur_list = $model_cart->listCart('db', array('buyer_id' => $_SESSION['member_id']));
        //数据库购物车已经有的商品，不再添加
        if (!empty($cart_cur_list) && is_array($cart_cur_list) && is_array($cart_new_list)) {
            foreach ($cart_new_list as $k => $v) {
                if (!is_numeric($k) || in_array($k, array_keys($cart_cur_list))) {
                    unset($cart_new_list[$k]);
                }
            }
        }
        //查询在购物车中,不是店铺自己的商品，未禁售，上架，有库存的商品,并加入DB购物车
        $mode_goods = $this->_getGoodsModel();
        $condition = array();
        if (!empty($_SESSION['store_id'])) {
            $condition['store_id'] = array('neq', $_SESSION['store_id']);
        }
        $condition['goods_id'] = array('in', array_keys($cart_new_list));
        $goods_list =$mode_goods->getGoodsOnlineList($condition);
        if (!empty($goods_list)) {
            foreach ($goods_list as $goods_info) {
                $goods_info['buyer_id'] = $member_info['member_id'];
                $model_cart->addCart($goods_info, 'db', $cart_new_list[$goods_info['goods_id']]['goods_num']);
            }
        }
        //最后清空登录前购物车内容
        $model_cart->clearCart($save_type);
    }

    /**
     * 电子邮箱检测
     * @return  void
     */
    public function check_emailOp()
    {
        if (C('ucenter_status')) {
            /**
             * 实例化Ucenter模型
             */
            $model_ucenter = $this->_getUcenterModel();
            $result = $model_ucenter->checkEmailExit(trim($_GET['email']));
            if ($result == 1) {
                echo 'true';
            } else {
                echo 'false';
            }

        } else {
            $model_member = $this->_getMemberModel();
            $check_member_email = $model_member->infoMember(array('member_email' => trim($_GET['email'])));
            if (is_array($check_member_email) and count($check_member_email) > 0) {
                echo 'false';
            } else {
                echo 'true';
            }
        }
    }

    /**
     * 忘记密码页面
     */
    public function forget_passwordOp()
    {
        /**
         * 读取语言包
         */
        Language::read('home_login_register');
        $_pic = @unserialize(C('login_pic'));
        if ($_pic[0] != '') {
            Tpl::output('lpic', UPLOAD_SITE_URL . '/' . ATTACH_LOGIN . '/' . $_pic[array_rand($_pic)]);
        } else {
            Tpl::output('lpic', UPLOAD_SITE_URL . '/' . ATTACH_LOGIN . '/' . rand(1, 4) . '.jpg');
        }
        Tpl::output('html_title', C('site_name') . ' - ' . Language::get('login_index_find_password'));
        Tpl::showpage('find_password');
    }

    /**
     * 找回密码的发邮件处理
     */
    public function find_passwordOp()
    {
        Language::read('home_login_register');
        $lang = Language::getLangContent();

        $result = chksubmit(true, true, 'num');
        if (!$result) {
            showDialog('非法提交');
        } elseif ($result === -11) {
            showDialog('非法提交');
        } elseif ($result === -12) {
            showDialog('验证码错误');
        }

        if (empty($_POST['username'])) {
            showDialog($lang['login_password_input_username']);
        }

        if (processClass::islock('forget')) {
            showDialog($lang['nc_common_op_repeat'], 'reload');
        }

        $member_model = $this->_getMemberModel();
        $member = $member_model->infoMember(array('member_name' => $_POST['username']));
        if (empty($member) or !is_array($member)) {
            processClass::addprocess('forget');
            showDialog($lang['login_password_username_not_exists'], 'reload');
        }

        if (empty($_POST['email'])) {
            showDialog($lang['login_password_input_email'], 'reload');
        }

        if (strtoupper($_POST['email']) != strtoupper($member['member_email'])) {
            processClass::addprocess('forget');
            showDialog($lang['login_password_email_not_exists'], 'reload');
        }
        processClass::clear('forget');

        //产生密码
        $new_password = random(15);
        if (!($member_model->updateMember(array('member_passwd' => md5($new_password)), $member['member_id']))) {
            showDialog($lang['login_password_email_fail'], 'reload');
        } else {
            if (C('ucenter_status')) {
                /**
                 * Ucenter处理
                 */
                $model_ucenter = $this->_getUcenterModel();
                $model_ucenter->userEdit(array('login_name' => $_POST['username'], '', 'password' => trim($new_password)));
            }
        }

        $cron_data = array('exetime' => TIMESTAMP, 'exeid' => $member['member_id'], 'type' => 2, 'code' => 'email_touser_find_password',
            'content' => array(array(
                'site_name' => $GLOBALS['setting_config']['site_name'],
                'site_url' => SHOP_SITE_URL,
                'user_name' => $_POST['username'],
                'new_password' => $new_password
            ), false));
        $this->addcron($cron_data, true);
        $extend_js = "<script type='text/javascript' src='" . SHOP_SITE_URL . "/index.php?act=login&op=send_email'></script>";
        $this->send_notice($member['member_id'], 'email_touser_find_password', array(
            'site_name' => $GLOBALS['setting_config']['site_name'],
            'site_url' => SHOP_SITE_URL,
            'user_name' => $_POST['username'],
            'new_password' => $new_password
        ), false);
        showMessage($lang['login_password_email_success'] . $extend_js, SHOP_SITE_URL);
    }

    /**
     * 检查用户是否登录
     * @param null|boolean $login
     * @return bool
     */
    protected function _checkLoginMember($login=null){
        //检查登录状态
        $isLogin=$_SESSION['is_login']==1;
        if($login===null){
            return $isLogin;
        }
        if($login=='index'&&$isLogin){
            header("Location: ".urlShop('shop','index'));
            return true;
        }
        if($login=='login'&&!$isLogin){
            header("Location: ".urlShop('login','index'));
            return false;
        }
        if($login=='login-index'){
            header("Location: ".urlShop($isLogin?'shop':'login','index'));
        }
        return $isLogin;
    }
    /**
     * 异步发送邮件
     */
    public function send_emailOp()
    {
        $this->_getMemberModel()->checkloginMember();

        $model_cron = Model('cron');
        $condition = array();
        $condition['type'] = 2;
        $condition['exeid'] = $_SESSION['member_id'];
        $condition['code'] = 'email_touser_find_password';
        $cron_info = $model_cron->getCronInfo();

        if (empty($cron_info)) return;

        $content = unserialize($cron_info['content']);

        if (!$content[1]) $content[1] = false;

        $this->send_notice($cron_info['exeid'], $cron_info['code'], $content[0], $content[1]);
        $model_cron->delCron(array('id'=>$cron_info['id']));
    }

}